<template>
  <view class="theme-detail">
    <CustomHeader :class="{ headWhite: headWhite }" />
    <clock-header
      ref="clockHeader"
      :theme-id="theme_id"
      :top-data-in="topData"
      :clock-detail="clockDetail"
      @pickChange="pickChange"
      @clockShare="holdOn"
      :mediaPlayFlag.sync="mediaPlayFlag"
      @onClose="rewardAgain"
    />
    <view
      id="clock"
      class="clock-info"
    >
      <SpecialBox
        class="special-box"
        :width="366"
        :height="76"
        :offset-x="12"
        :offset-y="8"
        :radius="8"
        :bgc="'linear-gradient(180deg, #FFF6D1 0%, #FFEEA9 100%)'"
        :bc="'#CB9064'"
      >
        <view class="clock-info__title">
          精选打卡
        </view>
      </SpecialBox>
      <view class="clock-info__list">
        <borderBox
          v-for="(item, index) in clockLog"
          :key="index"
          class="clock-info__list-item-wrap"
          style="margin-bottom:30rpx"
          :inside-padding="7"
          :bg-color="'#FFFBEA'"
          :bd-color="'#CB9064'"
        >
          <view class="clock-info__list-item">
            <ClockItem
              :item="item"
              :show-teacher-comment="true"
              :audio-index="index"
              :page-on-hide="pageOnHide"
              :mediaPlayFlag.sync="mediaPlayFlag"
              @generateClockPoster="generateClockPoster"
            />
          </view>
        </borderBox>

        <view
          v-if="!clockLog.length"
          class="clock-info__default"
        >
          <view>
            <image
              :lazy-load="true"
              :src="DEFAULT_IMG"
            />
          </view>
          <view v-if="!clockDetail.next_theme_id" class="clock-info__default--tip">
            还没有人打过卡哦~
          </view>
        </view>
        <view
          v-if="clockDetail.next_theme_id"
          class="more-theme"
          :style="`background-image:url(${SELECTOR_ARROWS})`"
          @tap="goNext"
        >
          查看其他主题打卡动态
        </view>
      </view>
    </view>
    <finish-button
      class="want-add"
      :width="690"
      :disabled="clockBtnStatus.dis"
      @click="clockBtnStatus.action()"
    >
      {{ clockBtnStatus.text }}
    </finish-button>
    <contactTeacher />
    <!-- 补签 -->
    <clock-reissue
      :show.sync="showSupplement"
      :theme-id="theme_id"
      :can-repair-times="canRepairTimes"
    />
    <!-- 分享图片 -->
    <ClockSign
      canvas-id="theme-detail"
      :show.sync="showShare"
      :student-id="clockSignInfo.studentId"
      :uuid="clockSignInfo.uuid"
      @clockShare="holdOn"
      @onClose="rewardAgain"
    />
    <AwardGive
      :show.sync="showAward"
      :position="'theme_detail'"
      @onClose="popClockSign"
    />
    <ClockConfirm
      :show-modal="isShowModal"
      @cancel="handleConfirmCancel"
      @confirm="handleConfirm"
    />
  </view>
</template>

<script>
import "./index.scss"
import Taro from "@tarojs/taro"
import CustomHeader from "_c/custom-header/index.vue"
import clockHeader from "_c/clock-header"
import clockReissue from "_c/clock-reissue"
import ClockItem from "_c/clock-item"
import borderBox from "_c/border-box/index"
import SpecialBox from "_c/special-box/index"
import { DEFAULT_IMG } from "@/config/clock-calendar"
import { SELECTOR_ARROWS } from "@/config/component-config/clock-header"
import { getCurrentInstance } from "@tarojs/taro"
import contactTeacher from "_c/contact-teacher/index"
import { themeDetail, choiceness, topData } from "_api/clock-in"
import { joinActivity } from "_api/activity"
import finishButton from "@/components/finish-button/index"
import ClockSign from "_c/generate-image"
import AwardGive from "@/components/award-give/index.vue"
import ClockConfirm from "_c/clock-confirm"

export default {
  name: "ThemeDetail",
  components: {
    clockHeader,
    ClockItem,
    SpecialBox,
    contactTeacher,
    CustomHeader,
    finishButton,
    clockReissue,
    ClockSign,
    AwardGive,
    ClockConfirm,
    borderBox
  },
  data () {
    return {
      DEFAULT_IMG,
      SELECTOR_ARROWS,
      clockLog: [],
      headWhite: false,
      clockDetail: {},
      theme_id: 0,
      isEnd: false,
      showSupplement: false,
      topData: [],
      status: 0,
      countdown: 0,
      clockSignInfo: {},
      showShare: false,
      showAward: false,
      clockOver: 0,
      canRewardAgain: false,
      canRepairTimes: 0,
      isShowModal: false,
      is_bounced: 0,
      pageOnHide: false,
      /* 在奖励弹窗之后能否弹出日签弹窗 */
      beforeDaySignImg:true,
      /* 媒体播放唯一标识 */
      mediaPlayFlag: -1
    }
  },
  computed: {
    //打卡按钮状态
    clockBtnStatus () {
      switch (this.status) {
        case 1: {
          return {
            text: "立即加入",
            dis: false,
            action: this.addActivity
          }
        }
        case 2: {
          return {
            text: "打卡",
            dis: false,
            action: this.clockIn
          }
        }
        case 3: {
          return {
            text: "已打卡",
            dis: true,
            action: () => { }
          }
        }
        case 4: {
          return {
            text: `倒计时${this.countdown}天开始`,
            small: true,
            dis: true,
            action: () => { }
          }
        }
        case 5: {
          return {
            text: "非打卡时段",
            dis: true,
            action: () => { }
          }
        }
        case 6: {
          return {
            text: "打卡已结束",
            dis: true,
            action: () => { }
          }
        }
        case 7: {
          return {
            text: "补签",
            dis: false,
            action: this.handleSupplement
          }
        }
        case 8: {
          return {
            text: "已补签",
            dis: true,
            action: () => { }
          }
        }
        default: {
          return {
            text: "加载中",
            dis: true,
            action: () => { }
          }
        }
      }
    }
  },
  onPageScroll: function ({ scrollTop }) {
    // Do something when page scroll
    this.headWhite = scrollTop > 20
  },
  async onLoad (opt) {
    this.theme_id = ~~opt.id
    this.getTopData()
    // await this.getClockInInfo();
  },
  onShow (opt) {
    /* Taro.eventCenter.once("handleClockOver", data => {
      this.clockOver = data;
    }); */
    this.clockOver = Taro.getStorageSync('clockOver')
    Taro.setStorageSync('clockOver', '')
    this.getClockInInfo()
    this.getChoiceness(1, true)
    this.showAward = true
    this.$refs.clockHeader.closeOtherVideo()
  },
  onHide () {
    this.clockOver = 0
    this.$store.commit('setMediaVideoFlag',-1)
    this.pageOnHide = !this.pageOnHide
  },
  onReachBottom: function () {
    // Do something when page reach bottom.
    if (this.isEnd) {
      return
    }
    this.getChoiceness(this.page)
  },
  methods: {
    /* 获取打卡详情信息 */
    async getClockInInfo () {
      let id = this.theme_id
      try {
        const { data } = await themeDetail({ id })
        this.clockDetail = data
        this.clockDetail.content = JSON.parse(this.clockDetail.content)
        this.status = data.status
        this.countdown = data.countdown
        this.canRepairTimes = data.can_repair_times
        this.is_bounced = data.is_bounced

        /**解锁打卡是不加载日签的 */
        /* data?.day_sign_status && (this.showAward = true); */
      } catch (err) {
        Taro.showToast({
          title: err.message,
          icon: "none",
          duration: 2000
        })
      }
    },
    getTopData () {
      topData({ theme_id: this.theme_id })
        .then(r => {
          this.topData = r.data
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          })
        })
    },
    getChoiceness (page, update = false) {
      choiceness({ theme_id: this.theme_id, page })
        .then(({ data }) => {
          update && (this.clockLog = [])
          this.clockLog.push(...data.data)
          console.log(this.clockLog)
          this.isEnd =
            data.meta.pagination.current_page >=
            data.meta.pagination.total_pages
          !this.isEnd && (this.page = data.meta.pagination.current_page + 1)
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          })
        })
    },
    pickChange (id) {
      this.theme_id = id
      this.getClockInInfo()
      this.getChoiceness(1, true)
    },
    addActivity () {
      joinActivity({ id: this.clockDetail.activity_id })
        .then(r => {
          // Taro.reLaunch({
          //   url: 'test?id=1'
          // })
          Taro.showToast({
            title: "加入成功",
            icon: "none",
            duration: 2000
          })
          this.getClockInInfo()
        })
        .catch(err => {
          Taro.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          })
          if (err.status_code === 4011) {
            this.getClockInInfo()
          }
        })
    },
    clockIn () {
      if(this.clockDetail.is_clock_full){
        Taro.showToast({
          title: "暂无可打卡主题，请稍后重试",
          icon: "none",
        })
        return
      }
      if (!this.is_bounced) {
        this.isShowModal = true
        return
      }
      
      Taro.navigateTo({
        url: `/pages/clock-in/index?id=${this.theme_id}`
      })
    },
    handleSupplement () {
      this.showSupplement = true
    },
    goNext () {
      Taro.redirectTo({
        url: `/pages/theme-detail/index?id=${this.clockDetail.next_theme_id}`
      })
    },
    /* 生成打卡海报 */
    generateClockPoster (item) {
      this.showShare = true
      this.clockSignInfo = {
        studentId: item.student_base_info.id,
        uuid: item.student_clock_info.uuid
      }
    },
    popClockSign () {
      this.beforeDaySignImg && this.clockOver && this.$refs.clockHeader.handlerClockSign()
    },
    holdOn () {
      this.canRewardAgain = true
    },
    rewardAgain () {
      console.log('日签关闭')
      this.canRewardAgain && (this.showAward = true)
      this.canRewardAgain = false
      this.beforeDaySignImg = false
    },
    handleConfirm () {
      this.isShowModal = false
      Taro.navigateTo({
        url: `/pages/group/home/index?id=${this.clockDetail.activity_id}`
      })
    },
    handleConfirmCancel () {
      this.isShowModal = false
      Taro.navigateTo({
        url: `/pages/clock-in/index?id=${this.theme_id}`
      })
    }
  }
};
</script>
